package com.epfresh.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.adapter.*;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.TagPager;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.widget.list.*;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.bean.*;
import com.epfresh.global.BaseFragment;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.app.Activity.RESULT_OK;

/**
 * Created by wzh on 2016/5/4.
 */
@SuppressLint("ValidFragment")
public class BookPayMonthFragment extends BaseFragment implements LoadMoreExpandableListView.IXListViewListener{
    protected View mainView;
    protected View vException;
    protected TextView tvExceptionDescription;
    protected ImageView ivExceptionIcon;
    private ProgressBar pb;
    private int requestSucceedCount = 0;
    private int PAGE_SIZE = 5;
    private TagPager tagPager = new TagPager();
    private LoadMoreExpandableListView lvContent;
    private List<BookPayMonth.ListBean> list = new ArrayList<>();
    BookPayMonthExpandListAdapter adapter;

    Context mContext;
    int type;//
    String timeValue;

    public BookPayMonthFragment() {
    }
    public BookPayMonthFragment(int newsType,String timeValue) {
        this.type =  newsType;
        this.timeValue = timeValue;
    }

    @Override
    public String getBaseTag() {
        return "BookPayMonthFragment";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_book_pay_month, container, false);
        mContext = this.getActivity();
        initView(view);
        adapter = new BookPayMonthExpandListAdapter(mContext,lvContent,list);
        lvContent.setAdapter(adapter);
        loadData(type, tagPager.getNumber());
        return view;
    }
    void initView(View v){

        initHeadView(v);
        vException = v.findViewById(R.id.v_exception);
        mainView = v.findViewById(R.id.fragment_ptr_home_ptr_frame);
        initException();
        lvContent = (LoadMoreExpandableListView)v.findViewById(R.id.lv_content);
        lvContent.setPullLoadEnable(true);
        lvContent.setXListViewListener(this);
        lvContent.setGroupIndicator(null);

    }
    private PtrFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, lvContent, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    private void initHeadView(View v) {
        ptrFrameLayout = (PtrFrameLayout) v.findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }

    boolean refreshFlag = false;
    public void refresh() {
        lvContent.resetNoMore();
        refreshFlag = true;
        loadData(type, 0);
    }

    @Override
    public void onLoadMore() {
        int number = tagPager.getNumber();
        loadData(type, number + 1);
    }

    public void updateViewStatus(RequestTag requestTag) {
        ptrFrameLayout.refreshComplete();
        if (tagPager.isLast()) {
            lvContent.noMore();
        } else {
            lvContent.stopLoadMore();
        }
    }

    void loadData(int type,int page){
        RequestEntityPurchase<Map<String, String>> entity = new RequestEntityPurchase<>();
        Map<String, String> map = new HashMap<>();
        map.put("queryDate", timeValue);
        map.put("type", ""+(type+1));
        map.put("pageSize","5");
        map.put("pageNumber",""+page);
        map.put("accountId", getUser().getAccountId());
        entity.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_income_incomeForPayMonth);
        entity.setParameters(map);
        RequestTag requestTag = new RequestTag();
        requestTag.tag = AppPurchaseRouterConstant.cmd_order_income_incomeForPayMonth;
        requestTag.action = page;
        requestTag.type = RequestTag.TYPE_CURRENT;
        request(entity, requestTag, onRequestListener);
    }


    public void initException() {
        tvExceptionDescription = (TextView) vException.findViewById(R.id.tv_exception);
        ivExceptionIcon = (ImageView) vException.findViewById(R.id.iv_exception);
        pb = (ProgressBar) vException.findViewById(R.id.pb);
    }


    public void showMainView() {
        vException.setVisibility(View.GONE);
        mainView.setVisibility(View.VISIBLE);
    }


    public void showExceptionView(int imgSrc, String text, int exceptionType) {
        if (imgSrc > 0) {

        }
        pb.setVisibility(View.GONE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.VISIBLE);
        ivExceptionIcon.setVisibility(View.VISIBLE);
        mainView.setVisibility(View.GONE);

        ivExceptionIcon.setImageResource(imgSrc);
        tvExceptionDescription.setText(text);
        tvExceptionDescription.setTag(exceptionType);
        ivExceptionIcon.setTag(exceptionType);
        tvExceptionDescription.setOnClickListener(this);
        ivExceptionIcon.setOnClickListener(this);
    }
    public void showProgressView() {

        pb.setVisibility(View.VISIBLE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.GONE);
        ivExceptionIcon.setVisibility(View.GONE);
        mainView.setVisibility(View.GONE);
    }


    OnRequestListener<BookPayMonth> onRequestListener = new OnRequestListener<BookPayMonth>() {
        @Override
        public BookPayMonth jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, BookPayMonth.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.order_no, "网络问题,请点击重试", HttpRequest.FAIL_NET_FAULT);
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();

            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.order_no, arg + "", HttpRequest.FAIL_DATA_FAULT);//arg + ",请点击重试"
            }
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
        }

        @Override
        public void onStart(Object tag) {
            if (requestSucceedCount == 0){
                showProgressView();
            }
        }

        @Override
        public void onResponse(ResponseEntity<BookPayMonth> response, Object tag) {
            hideProgressDialog();

            showMainView();
            requestSucceedCount ++;
            RequestTag requestTag = (RequestTag) tag;
            if (requestTag.action == 0) {
                list.clear();
            }
            BookPayMonth orderResponse = response.getResponseElement();
            List<BookPayMonth.ListBean> content = orderResponse.getList();
            tagPager.setLast(orderResponse.isIsLastPage());
            tagPager.setNumber(orderResponse.getPageNumber());
            tagPager.setSize(orderResponse.getPageSize());
            tagPager.setTotalElements(orderResponse.getTotalSize());
            list.addAll(content);
            adapter.notifyDataSetChanged();
            if(orderResponse.getPageNumber()==0){
                if(refreshFlag) {
                    lvContent.setSelection(0);
                    refreshFlag=false;
                }
            }
            updateViewStatus(requestTag);
            if(list.size()==0){
                showExceptionView(R.mipmap.order_no, "暂无订单", HttpRequest.FAIL_DATA_EMPTY);
            }
        }
    };
    @Override
    public void onResume() {
        super.onResume();
    }

    public void intoFresh(){
        showProgressView();
        refresh();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 0x001) {
            intoFresh();
        }
    }
}